package com.wenju.mqtt;

import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;


import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {
    private EditText wEtHost, wEtUserName, wEtpwd, wEtClientId, wEtMsg, wEtTopic;
    private LinearLayout wLyHost, wLyUserName, wLypwd, wLyClientId, wLyMsg, wLyTopic;
    private Button wBtnConnection, wBtnPublish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);

        wEtHost = findViewById(R.id.et_host);
        wLyHost = findViewById(R.id.ly_host);
        wEtUserName = findViewById(R.id.et_username);
        wLyUserName = findViewById(R.id.ly_username);
        wEtpwd = findViewById(R.id.et_pwd);
        wLypwd = findViewById(R.id.ly_pwd);
        wEtClientId = findViewById(R.id.et_client_id);
        wLyClientId = findViewById(R.id.ly_client_id);
        wEtMsg = findViewById(R.id.et_msg);
        wLyMsg = findViewById(R.id.ly_msg);
        wEtTopic = findViewById(R.id.et_topic);
        wLyTopic = findViewById(R.id.ly_topic);

        wBtnConnection = findViewById(R.id.btn_connection);
        wBtnPublish = findViewById(R.id.btn_publish);

        wBtnConnection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(wEtHost.getText()) || TextUtils.isEmpty(wEtUserName.getText()) || TextUtils.isEmpty(wEtpwd.getText()) || TextUtils.isEmpty(wEtClientId.getText()) || TextUtils.isEmpty(wEtTopic.getText())) {
                    Toast.makeText(MainActivity.this, "输入信息不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intentService = new Intent(MainActivity.this, MQTTService.class);
                    intentService.putExtra("HOST", wEtHost.getText().toString());
                    intentService.putExtra("USERNAME", wEtUserName.getText().toString());
                    intentService.putExtra("PWD", wEtpwd.getText().toString());
                    intentService.putExtra("CLIENTID", wEtClientId.getText().toString());
                    intentService.putExtra("TOPIC", wEtTopic.getText().toString());
                    startService(intentService);
                }
            }
        });
        wBtnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MQTTService.publish(wEtMsg.getText().toString());
            }
        });


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (!isNotificationEnabled(this)) {
                gotoSetNotification(this);
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!Settings.canDrawOverlays(MainActivity.this)) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提醒")
                        .setMessage("建议打开显示悬浮窗开关，方便使用其他App时能接到门铃电话")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 1);
                            }
                        }).setNegativeButton("取消", null)
                        .show();
            }
        }

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w("firebaseid", "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();

                        // Log and toast
//                        String msg = getString(R.string.msg_token_fmt, token);
                        Log.d("firebaseid", token);
                        Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //获取信息,启动页面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMqttMessage(MQTTMessage mqttMessage) {
        Log.i(MQTTService.TAG, "get message:" + mqttMessage.getMsg());
        Toast.makeText(this, mqttMessage.getMsg(), Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getApplication(), Main2Activity.class));
        createNotification(mqttMessage.getMsg());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getConnectionStatus(String connectionsStaus) {
        if ("0".equals(connectionsStaus)) {
            wLyHost.setVisibility(View.GONE);
            wLyUserName.setVisibility(View.GONE);
            wLypwd.setVisibility(View.GONE);
            wLyClientId.setVisibility(View.GONE);
            wLyTopic.setVisibility(View.GONE);
            wBtnConnection.setVisibility(View.GONE);

            wLyMsg.setVisibility(View.VISIBLE);
            wBtnPublish.setVisibility(View.VISIBLE);
            Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
        }
    }



    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void createNotification(String context) {
        //通知
        NotificationManager mNotificationManager1 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder;
        Intent intent = new Intent(MainActivity.this, Main2Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplication(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.FLAG_UPDATE_CURRENT
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel downloadChannel = new NotificationChannel(
                    "1", getString(R.string.push_title),
                    NotificationManager.IMPORTANCE_HIGH);
            downloadChannel.setSound(null, null);
            downloadChannel.setVibrationPattern(null);
            mNotificationManager1.createNotificationChannel(downloadChannel);
            builder = new Notification.Builder(getApplicationContext(), "1");
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setTicker("我是测试内容");
        builder.setContentText(context);
        builder.setNumber(0);
        builder.setShowWhen(true);
        builder.setOngoing(true);
        builder.setAutoCancel(false);
        builder.setContentIntent(pendingIntent);
        mNotificationManager1.notify(0x10000, builder.build());
    }

    private static void gotoSetNotification(Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    //判断该app是否打开了通知

    /**
     * 可以通过NotificationManagerCompat 中的 areNotificationsEnabled()来判断是否开启通知权限。NotificationManagerCompat 在 android.support.v4.app包中，是API 22.1.0 中加入的。而 areNotificationsEnabled()则是在 API 24.1.0之后加入的。
     * areNotificationsEnabled 只对 API 19 及以上版本有效，低于API 19 会一直返回true
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
            return areNotificationsEnabled;
        }

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (wBtnPublish.getVisibility() == View.VISIBLE) {
            wLyHost.setVisibility(View.VISIBLE);
            wLyUserName.setVisibility(View.VISIBLE);
            wLypwd.setVisibility(View.VISIBLE);
            wLyClientId.setVisibility(View.VISIBLE);
            wLyTopic.setVisibility(View.VISIBLE);
            wBtnConnection.setVisibility(View.VISIBLE);

            wLyMsg.setVisibility(View.GONE);
            wBtnPublish.setVisibility(View.GONE);
            return;
        }

        super.onBackPressed();
    }

}
